package com.nowcoder.community.service;

import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DataService {

    @Autowired
    private RedisTemplate redisTemplate;

    //生成指定日期格式的实例
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    //记录UV（UV中包含的日期为当前日期）
    public void recordUV(String ip){
        String redisKey = RedisKeyUtil.getUVKey(df.format(new Date()));
        //添加key，value为ip
        redisTemplate.opsForHyperLogLog().add(redisKey, ip);
    }

    public long calculateUV(Date startDate, Date endDate){
        //日期不能为空
        if(startDate == null || endDate == null){
            throw new IllegalArgumentException("参数不能为空!");
        }

        //整理日期范围内的key
        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        //记录每一天的key
        while(!calendar.getTime().after(endDate)){//如果startDate < endDate
            String key = RedisKeyUtil.getUVKey(df.format(calendar.getTime()));
            keyList.add(key);
            calendar.add(Calendar.DATE, 1);//将getTime的返回值加1
        }

        //合并这些数据
        String redisKey = RedisKeyUtil.getUVKey(df.format(startDate), df.format(endDate));
        redisTemplate.opsForHyperLogLog().union(redisKey, keyList.toArray());

        //返回统计结果
        return redisTemplate.opsForHyperLogLog().size(redisKey);
    }

    //将指定用户计入DAU
    public void recordDAU(int userId){
        String redisKey = RedisKeyUtil.getDAUKey(df.format(new Date()));
        redisTemplate.opsForValue().setBit(redisKey, userId, true);
    }

    //统计指定日期范围内的DAU
    public long calculateDAU(Date startDate, Date endDate){
        //日期不能为空
        if(startDate == null || endDate == null){
            throw new IllegalArgumentException("参数不能为空!");
        }

        //整理日期范围内的key
        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while(!calendar.getTime().after(endDate)){//如果startDate < endDate
            String key = RedisKeyUtil.getDAUKey(df.format(calendar.getTime()));
            keyList.add(key.getBytes());//将key转化成byte[]
            calendar.add(Calendar.DATE, 1);//将getTime的返回值加1
        }

        //指定日期范围内的DAU进行OR运算（统计用户的活跃度，只要一天中登录过就视为活跃）
        //将统计后的结果保存在缓存中（key为redisKey，value为统计数量）
        return (Long) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                String redisKey = RedisKeyUtil.getDAUKey(df.format(startDate), df.format(endDate));
                connection.bitOp(RedisStringCommands.BitOperation.OR,
                        redisKey.getBytes(), keyList.toArray(new byte[0][0]));
                return connection.bitCount(redisKey.getBytes());
            }
        });
    }
}
